package com.woniu.elderly.operation.service.impl;

import com.woniu.elderly.operation.exception.AlreadyLikedException;
import com.woniu.elderly.operation.service.OpelikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;



@Service
public class OpelikeServiceImpl implements OpelikeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 点赞
    @Override
    public void likeArticle(Long nid, Long eid) {
        //判断用户是否已经点赞，未点赞则添加执行点赞，否则提示已点赞，不能重复点赞
        if (!hasLiked(nid,eid)) {
            stringRedisTemplate.opsForHash().put("article:likes:" + nid, eid.toString(), "true");
        }else{
            throw new AlreadyLikedException("已点赞，不能重复点赞!");
        }
    }

    // 取消点赞
    @Override
    public void unlikeArticle(Long nid, Long eid) {
        stringRedisTemplate.opsForHash().delete("article:likes:" + nid, eid.toString());
    }

    // 检查用户是否已点赞
    @Override
    public boolean hasLiked(Long nid, Long eid) {
        return stringRedisTemplate.opsForHash().hasKey("article:likes:" + nid, eid.toString());
    }

    // 获取文章的点赞数（可选，如果需要）
    @Override
    public long getLikesCount(Long nid) {
        return stringRedisTemplate.opsForHash().size("article:likes:" + nid);
    }
}
